package CODEC.Impl;

import CODEC.Decoding;
import Utils.DecodingUtil;
import Utils.Util;
import domain.Message;
import domain.PDU.PDU;
import domain.PDU.Tag.TagType;
import domain.PDU.Type;
import domain.PDU.VariableBindings;

import java.util.HashMap;

/**
 * @Author: ylc
 * @Description:解码模块
 */
public class DecodingImpl implements Decoding {
    Util util = new Util();
    DecodingUtil deutil = new DecodingUtil();
    HashMap<Byte, String> codingTag = TagType.getCodingTag();

    @Override
    public Message getSnmpMessageValue(byte[] snmp) {
        Message message = new Message();
        int snmplen = 0;
        int index = 0;
        if( TagType.SEQUENCE.equals(codingTag.get(snmp[index])) ){
            snmplen = snmp[++index];
            index++;
        }
        // 获取version
        message.setVersion(deutil.getValue(snmp,index++));
        index += snmp[index] + 1;//下标移动到下一个T
        // 获取community
        message.setCommunity(deutil.getValue(snmp, index++));
        index += snmp[index] + 1;
        // 获取PDU
        message.setPdu(getPduValue(snmp, index));
        return message;
    }
    @Override
    public PDU getPduValue(byte[] packet, int index) {
        PDU pdu = new PDU();
        int pdulen = 0;
        // 获取PDU类型
        pdu.setPduType(Type.PDUTYPE[packet[index] & 3]);
        // 获取PDU长度
        pdulen = packet[++index];
        index++;
        // 获取requestId
        pdu.setRequestId(deutil.getValue(packet, index++));
        index += packet[index] + 1;
        // 获取errorStatus
        pdu.setErrorStatus(deutil.getValue(packet, index++));
        index += packet[index] + 1;
        // 获取errorIndex
        pdu.setErrorIndex(deutil.getValue(packet, index++));
        index += packet[index] + 1;
        //获取variableBindings
        pdu.setVariableBindings(getVarValue(packet, index));
        return pdu;
    }

    @Override
    public VariableBindings getVarValue(byte[] packet, int index) {
        VariableBindings var = new VariableBindings();
        int varlen = 0;
        int varCount = 0;
        if( TagType.SEQUENCE.equals(codingTag.get(packet[index])) ){
            varlen = packet[++index];
            index++;
        }
        if( TagType.SEQUENCE.equals(codingTag.get(packet[index])) ){
            varCount++;
            int var1len = packet[++index];
            index++;
        }
        // 获取Object Name
        var.setObjectName(deutil.getValue(packet, index++));
        index += packet[index] + 1;
        // 获取ValueType
        String valueType = codingTag.get(packet[index]);
        var.setValueType(valueType);
        // 获取Value
        if(valueType.equals("NULL")){
            var.setValue("0");
        }else{
            var.setValue(deutil.getValue(packet, index));
        }
        return var;
    }
}
